﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TRIMSDK;
using System.Web.Configuration;
using Microsoft.Win32;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        object recnorouteval = Page.RouteData.Values["RecNumber"];
        string errormsg = string.Empty;

        if (recnorouteval == null)
        {
            errormsg = "No recno parameter was passed.";
        }
        else
        {
            string recno = recnorouteval.ToString();
            //Response.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Database trim = new Database();
            trim.WebServerWorkPath = WebConfigurationManager.AppSettings["webserverworkpath"];
            trim.SetAsWebService();
            trim.Id = WebConfigurationManager.AppSettings["dbid"];
            trim.WorkgroupServerName = WebConfigurationManager.AppSettings["wgserver"];
            trim.WorkgroupServerPort = Int32.Parse(WebConfigurationManager.AppSettings["wgport"]);
            trim.Connect();

            Record rec = trim.GetRecord(recno);
            if (rec == null)
            {
                errormsg = string.Format("Could not find a record with number \"{0}\". Either it doesn't exist, or you don't have permission to view it.", recno);
            }
            else
            {
                if (!rec.IsElectronic)
                {
                    errormsg = string.Format("Record {0} does not have an electronic attachment", rec.Number);
                }
                else
                {
                    IStream s = rec.GetDocumentStream(null, false, null);

                    Response.ClearHeaders();
                    Response.AddHeader("Content-Disposition", "filename=" + rec.SuggestedFileName);
                    Response.AddHeader("Content-Length", rec.DocumentSize.ToString());
                    Response.Buffer = false;
                    Response.ContentType = GetContentType(rec.Extension);

                    uint BufferSize = 10000;
                    uint DocumentLength = (uint)rec.DocumentSize;
                    byte[] buffer = new byte[BufferSize];
                    uint bytesread;
                    uint totalread = 0;

                    Stream outstream = Response.OutputStream;

                    while (totalread < DocumentLength)
                    {
                        s.RemoteRead(out buffer[0], 10000, out bytesread);
                        if (bytesread < 10000)
                        {
                            for (uint i = 0; i < bytesread; i++)
                            {
                                outstream.WriteByte(buffer[i]);
                            }
                        }
                        else
                        {
                            outstream.Write(buffer, 0, 10000);
                        }
                        totalread += bytesread;
                    }
                    outstream.Close();
                    Response.Flush();
                    return;
                }
            }
        }
        Response.Write(errormsg);
    }

    private string GetContentType(string fileExtension)
    {
        string ct = Registry.GetValue(@"HKEY_CLASSES_ROOT\." + fileExtension.ToLower(), "Content Type", string.Empty) as string;

        if (ct.Length == 0)
        {
            ct = "application/octet-stream";
        }

        return ct;
    }

}
